package com.timemanager.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.timemanager.R;
import com.timemanager.db.TimeManagerDB;
import com.timemanager.model.Event;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 活动选择器
 * */

public class EventSelectorActivity extends AppCompatActivity {

    public static final int LEVEL_TYPE = 0;
    public static final int LEVEL_NAME = 1;
    private String [] types = {"学习", "工作", "生活", "娱乐", "运动", "其他"};
    private ArrayAdapter<String> adapter;
    private List<String> dataList = new ArrayList<String>();
    private TimeManagerDB timeManagerDB;
    private TextView titleText;
    private Button addEvent;
    private ListView listView;
    /**
     * 类型列表
     * */
    private List<String> typeList;
    /**
     * 活动列表
     * */
    private List<Event> eventList;
    /**
     * 用于判断从哪里转过来
     * */
    private String comeFrom;
    /**
     * 选中的类型
     * */
    private String selectedType;
    /**
     * 选中的活动
     * */
    private Event selectedEvent;
    /**
     * 当前选中级别
     * */
    private int currentLevel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //各种初始化
        setContentView(R.layout.activity_event_selector);
        comeFrom = getIntent().getStringExtra("come_from");
        titleText = (TextView) findViewById(R.id.title_text);
        addEvent = (Button) findViewById(R.id.add_event);
        listView = (ListView) findViewById(R.id.list_view);
        addEvent.setVisibility(View.INVISIBLE);
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
        listView.setAdapter(adapter);
        timeManagerDB = TimeManagerDB.getInstance(this);
        //监听ListView
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (currentLevel == LEVEL_TYPE) {
                    selectedType = typeList.get(position);
                    if (comeFrom.equals("add_event")) {
                        Intent intent = new Intent(EventSelectorActivity.this, AddEventActivity.class);
                        intent.putExtra("selected_type", selectedType);
                        startActivity(intent);
                        finish();
                    } else if (comeFrom.equals("edit_event")||comeFrom.equals("start_event")||comeFrom.equals("add_event_time")) {
                        queryEvents();
                    } else if (comeFrom.equals("edit_event_2")) {
                        Intent intent = new Intent(EventSelectorActivity.this, EditEventActivity.class);
                        intent.putExtra("event_id", getIntent().getIntExtra("event_id", 0));
                        intent.putExtra("selected_type", selectedType);
                        startActivity(intent);
                        finish();
                    }
                }
                else if (currentLevel == LEVEL_NAME) {
                    selectedEvent = eventList.get(position);
                    if (comeFrom.equals("edit_event")) {
                        showItemDialog(selectedType, selectedEvent);
                    } else if (comeFrom.equals("start_event")) {
                        Intent intent = new Intent(EventSelectorActivity.this, StartEventActivity.class);
                        intent.putExtra("event_id", selectedEvent.getId());
                        intent.putExtra("event_name", selectedEvent.getName());
                        startActivity(intent);
                    } else if(comeFrom.equals("add_event_time")) {
                        Intent intent = new Intent(EventSelectorActivity.this, AddEventTimeActivity.class);
                        intent.putExtra("event_id", selectedEvent.getId());
                        intent.putExtra("event_name", selectedEvent.getName());
                        startActivity(intent);
                    }
                }
            }
        });
        queryTypes();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        queryEvents();
    }
    @Override
    public void onBackPressed() {
        if (currentLevel == LEVEL_NAME) {
            queryTypes();
        }
        else {
            finish();
        }
    }

    /**
     * 加载Types
     * */
    private void queryTypes() {
        dataList.clear();
        typeList = Arrays.asList(types);
        dataList.addAll(typeList);
        adapter.notifyDataSetChanged();
        listView.setSelection(0);
        currentLevel = LEVEL_TYPE;
        titleText.setText("请选择活动类型：");
    }
    /**
     * 加载EventList
     */
    private void queryEvents() {
        eventList = timeManagerDB.loadEvents(selectedType);
        dataList.clear();
        for (Event event : eventList) {
            dataList.add(event.getName());
        }
        adapter.notifyDataSetChanged();
        listView.setSelection(0);
        if (comeFrom.equals("start_event")) {
            titleText.setText("请选择一项活动或新增一项活动：");
            titleText.setTextSize(17);
            addEvent.setVisibility(View.VISIBLE);//将”新增活动“按钮设为可见
            addEvent.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(EventSelectorActivity.this, AddEventActivity2.class);
                    intent.putExtra("selected_type",selectedType);
                    startActivity(intent);
                }
            });
        } else if (comeFrom.equals("edit_event")){
            titleText.setText("请选择将要操作的活动：");
            titleText.setTextSize(20);
        }
        currentLevel = LEVEL_NAME;
    }
    /**
     * 选择将要对数据进行的操作
     */
    private void showItemDialog(final String selectedType, final Event selectedEvent) {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(EventSelectorActivity.this);
        dialogBuilder.setTitle("选择将要对[" + selectedType + "]类的[" + selectedEvent.getName() + "]活动操作：");
        final String[] operations = {"修改", "删除"};
        dialogBuilder.setItems(operations, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (operations[which].equals("修改")) {
                    Intent intent = new Intent(EventSelectorActivity.this, EventSelectorActivity.class);
                    intent.putExtra("come_from", "edit_event_2");
                    intent.putExtra("event_id", selectedEvent.getId());
                    startActivity(intent);
                }
                else if (operations[which].equals("删除")) {
                    if (timeManagerDB.deleteEvent(selectedEvent.getId())) {
                        Toast.makeText(EventSelectorActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                        queryEvents();
                    } else {
                        Toast.makeText(EventSelectorActivity.this, "删除失败，该活动已有相关记录，不可删除", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        dialogBuilder.show();
    }
}
